package com.wwg.base.file.zip;


import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @description:
 * @date: 2020/12/3 11:53
 * @author: xubo
 */
public class ZipUtils {

    /**
     * zip解压
     * @param srcFile        zip源文件
     * @param destDirPath     解压后的目标文件夹
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static void unZipFiles(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 开始解压
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
//            Enumeration<?> entries = zipFile.getEntries();
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                System.out.println(entry.getName());
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在

                    if(!targetFile.getParentFile().exists()){

                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解压完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param filePath
     * 临时文件的删除
     * 删除文件夹里面子目录
     * 再删除文件夹
     */
    public static void deleteFiles(String filePath) {
        File file = new File(filePath);
        if ((!file.exists()) || (!file.isDirectory())) {
            System.out.println("file not exist");
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (filePath.endsWith(File.separator)) {
                temp = new File(filePath + tempList[i]);
            }
            else {
                temp = new File(filePath + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                deleteFiles(filePath + "/" + tempList[i]);
            }
        }
        // 空文件的删除
        file.delete();
    }

    public static void main(String[] args) throws IOException {
        test1();

//        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("C:\\Users\\wuwei\\Desktop", "Desktop.zip")));
//        String dir = "C:\\Users\\wuwei\\Desktop\\";
//        test2(zos, dir + "123 - 副本 (2).xls");
//        test2(zos,dir + "123 - 副本.xls");
//        test2(zos,dir + "123.xls");

//        test3();
    }

    private static void test1() {
        /*
         *创建临时文件夹
         * 解压文件
         */
        File file = new File("C:\\Users\\wuwei\\Desktop", "Desktop.zip");

        String fileName = file.getName();
        String path = "C:\\Users\\wuwei\\Desktop\\zip\\"; //解压后文件存放位置
        File dir = new File(path);
        dir.mkdirs();
        String filePath = "C:\\Users\\wuwei\\Desktop\\zip2\\";//临时用于存放压缩包的位置
        File fileDir = new File(filePath);
        fileDir.mkdirs();
        File saveFile = new File(fileDir, fileName);//将压缩包写入到指定位置
        try {
            //把上传的压缩包写入到临时文件夹中
//            file.transferTo(saveFile);
            file.renameTo(saveFile);
            String newFilePath = filePath + fileName;
            File zipFile = new File(newFilePath);
            //解压文件，传入需要解压的文件 和解压完后文件放的地方
            ZipUtils.unZipFiles(zipFile, path);

            //解压完成,上传文件夹中的图片
            //上传图片,先过滤不符合条件的图片,封装到结果集中
//            R<ImportSupplierSkuImagesResult> result = spuService.importImages(path);
            //程序结束时，删除临时文件
            ZipUtils.deleteFiles(filePath);//删除压缩包文件夹
            ZipUtils.deleteFiles(path);//删除解压文件夹**
            //返回结果
//            return result;
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


    /**
     * @param zos
     * @return
     * @throws IOException
     * @description: 转为压缩流
     */
    private static void test2(ZipOutputStream zos,String fileUrl) throws IOException {
        File file = new File(fileUrl);
        ZipEntry zipEntry = new ZipEntry(file.getName());
        zos.putNextEntry(zipEntry);
//        InputStream fis = FileUtils.getInputStreamByFileUrl(fileUrl);
        InputStream fis = new FileInputStream(file);
        // 因为 URL 为 OSS 地址，故此处也可以直接从通过 OSS API 获取要下载的内容（走内网的话其两种方式的效率差不多）
    /*OSSClient ossClient=  ossUtil.getOSSClient();
    OSSObject ossObject = ossClient.getObject(ossPropResource.getUserStorageOssBucketName(), StringUtils.substringAfterLast(fileUrl, ".com/"));
    InputStream fis = ossObject.getObjectContent();*/
        if (fis == null) {
            return;
        }
        byte[] buffer = new byte[2048];
        int r;
        while ((r = fis.read(buffer)) != -1) {
            zos.write(buffer, 0, r);
        }
        fis.close();
        //  注意写完一个文件，需要关闭这个文件，再写下一个
        zos.closeEntry();
        zos.flush();
    }


    public static void test3() throws IOException {

        File file1 = new File("C:\\Users\\wuwei\\Desktop\\Desktop.zip");
        FileInputStream fileInputStream = new FileInputStream(file1);
//        ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
        ZipFile zipFile = new ZipFile(file1);

        File file = new File("C:\\Users\\wuwei\\Desktop\\Desktop1.zip");
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file));
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        ZipEntry nextEntry;

        while ((nextEntry = entries.nextElement()) != null){
            zipOutputStream.putNextEntry(nextEntry);
            InputStream inputStream = zipFile.getInputStream(nextEntry);
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes)!= -1){
                zipOutputStream.write(bytes,0,bytes.length);
            }
            zipOutputStream.closeEntry();
            zipOutputStream.flush();
        }

    }

}


